package com.tianluo.tianluobookstore.controller.user;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.tianluo.tianluobookstore.config.AesConfig;
import com.tianluo.tianluobookstore.domain.dto.UserInfoDTO;
import com.tianluo.tianluobookstore.domain.view.HomePageVO;
import com.tianluo.tianluobookstore.domain.view.UserInfoVO;
import com.tianluo.tianluobookstore.enums.CommonCodeEnum;
import com.tianluo.tianluobookstore.enums.UserCodeEnum;
import com.tianluo.tianluobookstore.request.EditUserRequest;
import com.tianluo.tianluobookstore.request.LoginRequest;
import com.tianluo.tianluobookstore.request.RegisterUserRequest;
import com.tianluo.tianluobookstore.response.BaseResponse;
import com.tianluo.tianluobookstore.service.BookStoreService;
import com.tianluo.tianluobookstore.service.RedisService;
import com.tianluo.tianluobookstore.service.UserService;
import com.tianluo.tianluobookstore.util.AESUtil;
import com.tianluo.tianluobookstore.util.JwtTokenUtil;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AesConfig aesConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisService redisService;

    @Autowired
    private BookStoreService bookStoreService;

    @PostMapping("/registerUser")
    public BaseResponse<UserInfoVO> addUser(@Validated @RequestBody RegisterUserRequest userRequest, BindingResult result) {

        System.out.println("666:"+userRequest.getUserName());

        List<FieldError> fieldErrors = result.getFieldErrors();
        if (!fieldErrors.isEmpty()) {
            // 创建BaseResponse对象，设置错误消息，不设置data
            BaseResponse<UserInfoVO> response = new BaseResponse<>();
            response.setCode(CommonCodeEnum.PARAM_ERROR.getCode()); // 通常是HTTP 400 Bad Request
            response.setMessage(fieldErrors.get(0).getDefaultMessage());
            return response;
        }

//        if (StringUtils.isEmpty(userRequest.getUserName())) {
//            return "用户名不能为空";
//        }
//        if (StringUtils.isEmpty(userRequest.getPhone())) {
//            return "手机号不能为空";
//        }
//        if (userRequest.getPhone().length() > 11) {
//            return "手机号不能超过11";
//        }
//        if (StringUtils.isEmpty(userRequest.getEmail())) {
//            return "邮箱不能为空";
//        }

//        System.out.println(userRequest.getPassword());
//        try {
//            String test = AESUtil.encrypt(userRequest.getPassword(), aesConfig.getSecretKey(), aesConfig.getInitVector());
//            System.out.println("密码加密:" + test);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }

        //我提前加密得到的：BEWbxhutStNh//4dtVimww==
        //大家可以用postman请求，密码传这个就好
        UserInfoVO userInfoVO = new UserInfoVO();

        //省略其他参数校验
        UserInfoDTO userInfoDTO = userService.queryUsername(userRequest.getUserName());
        if (Objects.nonNull(userInfoDTO)) {
            BeanUtils.copyProperties(userInfoDTO, userInfoVO);
            return BaseResponse.success(userInfoVO);
        }

        String password = decryptPassword(userRequest.getPassword());
        //密码加密存储
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
        userRequest.setPassword(hashedPassword);

        UserInfoDTO userInfoDTOResult = userService.registerUser(userRequest);
        BeanUtils.copyProperties(userInfoDTOResult, userInfoVO);

        return BaseResponse.success(userInfoVO);
    }

    @PostMapping("/login")
    public BaseResponse<String> login(@RequestBody  LoginRequest loginRequest) throws Exception {

        UserInfoDTO userInfo = userService.queryByPhone(loginRequest.getPhone());
        // 这里验证用户名和密码
        if (!checkPassword(loginRequest, userInfo)) {
            return BaseResponse.fail(UserCodeEnum.PASSWORD_NOT_RIGHT);
        }
        // 假设验证成功，生成JWT并返回给客户端,打算用手机号作为userId
        String token = jwtTokenUtil.generateToken(loginRequest.getPhone());

        String tid = UUID.randomUUID().toString();
        //保存到redis
        redisService.setNx(loginRequest.getPhone(), tid, 1800);

        return BaseResponse.success(token);
    }

    private boolean checkPassword(LoginRequest loginRequest, UserInfoDTO userInfo) {
        String password = decryptPassword(loginRequest.getPassword());
        return BCrypt.checkpw(password, userInfo.getPassword());
    }

    @RequestMapping("editUser")
    public String editUser(@Validated EditUserRequest editUser, BindingResult result) {

        List<FieldError> fieldErrors = result.getFieldErrors();
        if (!fieldErrors.isEmpty()) {
            return fieldErrors.get(0).getDefaultMessage();
        }

//        if (StringUtils.isEmpty(editUser.getUserName())) {
//            return "用户名不能为空";
//        }
//        if (StringUtils.isEmpty(editUser.getPhone())) {
//            return "手机号不能为空";
//        }
//        if (editUser.getPhone().length() > 11) {
//            return "手机号不能超过11";
//        }
//
//        if (StringUtils.isEmpty(editUser.getEmail())) {
//            return "邮箱不能为空";
//        }

        //省略其他参数校验
        //todo 编辑用户信息表
        return "SUCCESS";
    }

    @RequestMapping("queryUserInfo")
    public BaseResponse<UserInfoVO> queryUserInfo(@RequestAttribute("phoneNumber") String phoneNumber) {
        //解析出手机号，根据手机号来查询用户信息
        //因为行内好像都加Bearer 拼接到token，所以我们也来，哈哈
//        String jwt = token.replace("Bearer ", "");
//        Claims claims = jwtTokenUtil.extractClaims(jwt);
//        //我们登录时，把手机号塞进去，因为可以解析出来，查询用户信息
//        String phoneNumber = claims.getSubject();

        System.out.println("phoneNumber:" + phoneNumber);

        UserInfoDTO userInfo = userService.queryByPhone(phoneNumber);
        if (Objects.nonNull(userInfo)) {
            UserInfoVO userInfoVO = new UserInfoVO();
            BeanUtils.copyProperties(userInfo, userInfoVO);
            return BaseResponse.success(userInfoVO);
        }

        //查不到就报错
        return BaseResponse.fail(UserCodeEnum.USER_NOT_FOUND);
    }

    @RequestMapping("homePage")
    public BaseResponse<HomePageVO>  homePage(@RequestAttribute("phoneNumber") String phoneNumber) {
        BaseResponse<HomePageVO> homePage = BaseResponse.success(bookStoreService.homePage(phoneNumber));
        System.out.println(JSONUtil.toJsonStr(homePage));
        return homePage;
    }

    private String decryptPassword(String password){
        String passwordPlain = null;
        try {
            passwordPlain = AESUtil.decrypt(password, aesConfig.getSecretKey(), aesConfig.getInitVector());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return passwordPlain;
    }

}
